package com.LocalMarket.LocalMarketClient.Utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class ConnectionHandler {
	DatagramSocket udpSocket;
	InetAddress serverAddress;
	int serverPort;
	
	public ConnectionHandler(String address, int port){
		try {
			this.udpSocket = new DatagramSocket();
			this.serverAddress = InetAddress.getByName(address);
			this.serverPort=port;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	
	public boolean SendMessage(String messageToSend){
		byte[] rawMessage = messageToSend.getBytes();
		if (this.udpSocket==null || rawMessage==null || this.serverAddress==null)
			return false;
			
		DatagramPacket packetToSend = new DatagramPacket(rawMessage, rawMessage.length, this.serverAddress, this.serverPort);
		try {
			this.udpSocket.send(packetToSend);
		} catch (IOException e) {
			System.out.println("I can't send the UDP packet");
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public static void main(String[] args){
		ConnectionHandler testClient = new ConnectionHandler("192.168.1.98", 21567);
		System.out.println("Client created!");
		testClient.SendMessage("CMD:close");
		System.out.println("Message sent!");
	}

}
